package controller

import (
	"denglibin.io/common/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"go.web.demo.com/web/config"
	"go.web.demo.com/web/model"
	"path"
	"time"
)

// FileRoute 路由
func FileRoute(g *gin.RouterGroup) {

	g.POST("/upload", UploadFile)
	g.GET("/down", DownloadFile)
	g.GET("/view", ViewFile)
	g.GET("/video", Video)
}

// UploadFile 文件上传
func UploadFile(c *gin.Context) {
	//f, err := c.FormFile("file")

	f, err := c.MultipartForm()
	if err != nil {
		logrus.Error(err)
		SuccessJson(c, model.Fail("上传失败"))
		return
	}
	var fileUris = make([]string, 0, 8)
	var fileName string
	day := fmt.Sprint(time.Now().Format("2006-01-02"))
	dir := config.GetApplicationConfig().UploadDir + "/" + day
	util.CreateDir(dir)
	for key, arr := range f.File {
		fmt.Println("key", key)
		for _, file := range arr {

			fileName = dir + "/" + fmt.Sprintf("%d-%s", time.Now().Unix(), util.GetRandomStr(10)+path.Ext(file.Filename))
			err = c.SaveUploadedFile(file, fileName)
			if err != nil {
				panic(err)
			}
			fileUris = append(fileUris, fileName)
		}
	}
	SuccessJson(c, model.Success(fileUris))
}

// DownloadFile 下载文件
func DownloadFile(c *gin.Context) {
	filePath := "C:\\Users\\mdjro\\Desktop\\成绩表.xls"

	c.Header("Content-Type", "application/octet-stream")
	c.Header("Content-Disposition", "attachment; filename=成绩表.xls")
	c.Header("Content-Transfer-Encoding", "binary")
	c.File(filePath)
}

// ViewFile 查看文件
func ViewFile(c *gin.Context) {
	filePath := "C:\\Users\\mdjro\\Desktop\\2.jpg"
	c.File(filePath)
}

// Video 视频播放
func Video(c *gin.Context) {
	filePath := "C:\\Users\\mdjro\\Desktop\\12.mp4"
	c.File(filePath)
}
